package dca.sistemascontrole.view;

import dca.sistemascontrole.dao.GraphicDataManager;
import dca.sistemascontrole.exception.LogManager;
import dca.sistemascontrole.handler.HandlerMainFrame;
import dca.sistemascontrole.malhadecontrole.MalhaDeControle;
import dca.sistemascontrole.sinais.Sinal;
import dca.sistemascontrole.util.ControleConstantes;
import dca.sistemascontrole.util.XMLManager;
import dca.sistemascontrole.view.components.VariaveisObservaveis;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

/**
 *
 * @author Rafael
 */
public class MainFrame extends javax.swing.JFrame {

    private int malhaAtiva;
    private int tipoDeSinal;
    private boolean running;
    private HandlerMainFrame handlerMainFrame;
    private static final String TITULO_TANQUE_SUPERIOR = "Tanquer Superior";
    private static final String TITULO_TANQUE_INFERIOR = "Tanquer Inferior";

    public MainFrame() {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        initComponents();

        lblTanqueSuperior.setText(TITULO_TANQUE_SUPERIOR + " - 0.000 cm");
        lblTanqueInferior.setText(TITULO_TANQUE_INFERIOR + " - 0.000 cm");
    }

    public MainFrame(HandlerMainFrame handlerMainFrame) {
        this();
        this.handlerMainFrame = handlerMainFrame;

        setMalhaAberta();
        txtPeriodo.setEnabled(false);
    }

    public void setVariaveisObsrvaveis(VariaveisObservaveis variaveisObservaveis) {
        float porcentagemTanqueSuperior = (float) (variaveisObservaveis.getNivelTankSuperior() / (float) ControleConstantes.ALTURA_TANQUE);
        lblTanqueSuperior.setText(String.format("%s - %.3f cm", TITULO_TANQUE_SUPERIOR, variaveisObservaveis.getNivelTankSuperior()));
        pnlGraficoSensorSuperior.addValue(variaveisObservaveis.getNivelTankSuperior());
        sensorAlturaSuperior.setPorcentagemFluido(porcentagemTanqueSuperior);
        sensorAlturaSuperior.repaint();


        float porcentagemTanqueInferior = (float) (variaveisObservaveis.getNivelTankInfeior() / (float) ControleConstantes.ALTURA_TANQUE);
        lblTanqueInferior.setText(String.format("%s - %.3f cm", TITULO_TANQUE_INFERIOR, variaveisObservaveis.getNivelTankInfeior()));
        pnlGraficoSensorInferior.addValue(variaveisObservaveis.getNivelTankInfeior());
        sensorAlturaInferior.setPorcentagemFluido(porcentagemTanqueInferior);
        sensorAlturaInferior.repaint();


        pnlGraficoSinalControle.addValue(variaveisObservaveis.getTensaoEscrita());
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();
        jPanel2 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        pnlGraficoSensorInferior = new dca.sistemascontrole.view.components.GraphicPanel();
        pnlGraficoSinalControle = new dca.sistemascontrole.view.components.GraphicPanel();
        pnlGraficoSensorSuperior = new dca.sistemascontrole.view.components.GraphicPanel();
        jPanel7 = new javax.swing.JPanel();
        radioMalhaAberta = new javax.swing.JRadioButton();
        radioMalhaFechada = new javax.swing.JRadioButton();
        jPanel8 = new javax.swing.JPanel();
        jLabel8 = new javax.swing.JLabel();
        txtSetpoint = new javax.swing.JTextField();
        btnDefinitSetpoint = new dca.sistemascontrole.view.components.CustomButton();
        jPanel9 = new javax.swing.JPanel();
        jPanel10 = new javax.swing.JPanel();
        radioDegrau = new javax.swing.JRadioButton();
        radioSenoidal = new javax.swing.JRadioButton();
        radioQuadrada = new javax.swing.JRadioButton();
        radioDenteSerra = new javax.swing.JRadioButton();
        radioAleatorio = new javax.swing.JRadioButton();
        jPanel11 = new javax.swing.JPanel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        txtAmplitude = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        txtPeriodo = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        txtTempoAtuacao = new javax.swing.JTextField();
        jLabel14 = new javax.swing.JLabel();
        btnSend = new dca.sistemascontrole.view.components.CustomButton();
        sensorAlturaSuperior = new dca.sistemascontrole.view.components.SensorAltura();
        sensorAlturaInferior = new dca.sistemascontrole.view.components.SensorAltura();
        lblTanqueSuperior = new javax.swing.JLabel();
        lblTanqueInferior = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        btnInterromper = new dca.sistemascontrole.view.components.CustomButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        menuSalvar = new javax.swing.JMenuItem();
        menuCarregar = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        menuConfigurarPortas = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Análise das Variáveis"));

        pnlGraficoSensorInferior.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        pnlGraficoSensorInferior.setTitle("Nível no Tanque Inferior");

        pnlGraficoSinalControle.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        pnlGraficoSinalControle.setTitle("Sinal de Controle");

        pnlGraficoSensorSuperior.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        pnlGraficoSensorSuperior.setTitle("Nível no Tanque Superior");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(pnlGraficoSensorInferior, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(pnlGraficoSinalControle, javax.swing.GroupLayout.DEFAULT_SIZE, 778, Short.MAX_VALUE)
                    .addComponent(pnlGraficoSensorSuperior, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnlGraficoSensorSuperior, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlGraficoSensorInferior, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlGraficoSinalControle, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel7.setBackground(new java.awt.Color(255, 255, 255));

        radioMalhaAberta.setBackground(new java.awt.Color(255, 255, 255));
        buttonGroup2.add(radioMalhaAberta);
        radioMalhaAberta.setSelected(true);
        radioMalhaAberta.setText("Ativar Malha Aberta");
        radioMalhaAberta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioMalhaAbertaActionPerformed(evt);
            }
        });

        radioMalhaFechada.setBackground(new java.awt.Color(255, 255, 255));
        buttonGroup2.add(radioMalhaFechada);
        radioMalhaFechada.setText("Ativar Malha Fechada");
        radioMalhaFechada.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioMalhaFechadaActionPerformed(evt);
            }
        });

        jPanel8.setBackground(new java.awt.Color(255, 255, 255));
        jPanel8.setBorder(javax.swing.BorderFactory.createTitledBorder("Malha Fechada"));

        jLabel8.setText("Setpoint:");

        btnDefinitSetpoint.setBackground(new java.awt.Color(250, 250, 250));
        btnDefinitSetpoint.setText("Definir");
        btnDefinitSetpoint.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDefinitSetpointActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
        jPanel8.setLayout(jPanel8Layout);
        jPanel8Layout.setHorizontalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtSetpoint)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnDefinitSetpoint, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel8Layout.setVerticalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel8Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel8)
                        .addComponent(txtSetpoint, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(btnDefinitSetpoint, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel8Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnDefinitSetpoint, jLabel8, txtSetpoint});

        jPanel9.setBackground(new java.awt.Color(255, 255, 255));
        jPanel9.setBorder(javax.swing.BorderFactory.createTitledBorder("Malha Aberta"));

        jPanel10.setBackground(new java.awt.Color(255, 255, 255));
        jPanel10.setBorder(javax.swing.BorderFactory.createTitledBorder("Sinais de Controle"));

        radioDegrau.setBackground(new java.awt.Color(255, 255, 255));
        buttonGroup1.add(radioDegrau);
        radioDegrau.setSelected(true);
        radioDegrau.setText("Degrau");
        radioDegrau.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioDegrauActionPerformed(evt);
            }
        });

        radioSenoidal.setBackground(new java.awt.Color(255, 255, 255));
        buttonGroup1.add(radioSenoidal);
        radioSenoidal.setText("Senoidal");
        radioSenoidal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioSenoidalActionPerformed(evt);
            }
        });

        radioQuadrada.setBackground(new java.awt.Color(255, 255, 255));
        buttonGroup1.add(radioQuadrada);
        radioQuadrada.setText("Quadrada");
        radioQuadrada.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioQuadradaActionPerformed(evt);
            }
        });

        radioDenteSerra.setBackground(new java.awt.Color(255, 255, 255));
        buttonGroup1.add(radioDenteSerra);
        radioDenteSerra.setText("Dente de Serra");
        radioDenteSerra.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioDenteSerraActionPerformed(evt);
            }
        });

        radioAleatorio.setBackground(new java.awt.Color(255, 255, 255));
        buttonGroup1.add(radioAleatorio);
        radioAleatorio.setText("Aleatório");
        radioAleatorio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioAleatorioActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
        jPanel10.setLayout(jPanel10Layout);
        jPanel10Layout.setHorizontalGroup(
            jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel10Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(radioDenteSerra, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(radioDegrau, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel10Layout.createSequentialGroup()
                        .addComponent(radioSenoidal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(radioQuadrada, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel10Layout.createSequentialGroup()
                        .addComponent(radioAleatorio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(101, 101, 101)))
                .addContainerGap())
        );
        jPanel10Layout.setVerticalGroup(
            jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel10Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radioDegrau)
                    .addComponent(radioSenoidal)
                    .addComponent(radioQuadrada))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radioDenteSerra)
                    .addComponent(radioAleatorio))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel11.setBackground(new java.awt.Color(255, 255, 255));
        jPanel11.setBorder(javax.swing.BorderFactory.createTitledBorder("Configurar Sinal"));

        jLabel9.setText("Amplitude:");

        jLabel10.setText("Período:");

        jLabel11.setText("(V)");

        jLabel12.setText("(s)");

        jLabel13.setText("Tempo de Atuação:");

        jLabel14.setText("(s)");

        btnSend.setBackground(new java.awt.Color(250, 250, 250));
        btnSend.setText("Enviar");
        btnSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11);
        jPanel11.setLayout(jPanel11Layout);
        jPanel11Layout.setHorizontalGroup(
            jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel11Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel11Layout.createSequentialGroup()
                        .addComponent(jLabel10)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtPeriodo, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel12))
                    .addGroup(jPanel11Layout.createSequentialGroup()
                        .addComponent(jLabel13)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtTempoAtuacao, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel14)
                        .addGap(82, 82, 82)
                        .addComponent(btnSend, javax.swing.GroupLayout.DEFAULT_SIZE, 55, Short.MAX_VALUE))
                    .addGroup(jPanel11Layout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtAmplitude, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel11)))
                .addContainerGap())
        );

        jPanel11Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel10, jLabel9});

        jPanel11Layout.setVerticalGroup(
            jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel11Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(txtAmplitude, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel10)
                    .addComponent(txtPeriodo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel12))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel13)
                    .addComponent(txtTempoAtuacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel14)
                    .addComponent(btnSend, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
        jPanel9.setLayout(jPanel9Layout);
        jPanel9Layout.setHorizontalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel11, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel10, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel9Layout.setVerticalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel11, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        sensorAlturaSuperior.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout sensorAlturaSuperiorLayout = new javax.swing.GroupLayout(sensorAlturaSuperior);
        sensorAlturaSuperior.setLayout(sensorAlturaSuperiorLayout);
        sensorAlturaSuperiorLayout.setHorizontalGroup(
            sensorAlturaSuperiorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 205, Short.MAX_VALUE)
        );
        sensorAlturaSuperiorLayout.setVerticalGroup(
            sensorAlturaSuperiorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 148, Short.MAX_VALUE)
        );

        sensorAlturaInferior.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout sensorAlturaInferiorLayout = new javax.swing.GroupLayout(sensorAlturaInferior);
        sensorAlturaInferior.setLayout(sensorAlturaInferiorLayout);
        sensorAlturaInferiorLayout.setHorizontalGroup(
            sensorAlturaInferiorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 205, Short.MAX_VALUE)
        );
        sensorAlturaInferiorLayout.setVerticalGroup(
            sensorAlturaInferiorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        lblTanqueSuperior.setText("Tanquer Superior");

        lblTanqueInferior.setText("Tanquer Inferior");

        btnInterromper.setBackground(new java.awt.Color(250, 250, 250));
        btnInterromper.setText("Interromper");
        btnInterromper.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnInterromperActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
        jPanel7.setLayout(jPanel7Layout);
        jPanel7Layout.setHorizontalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1)
                    .addComponent(jPanel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel7Layout.createSequentialGroup()
                        .addComponent(radioMalhaAberta)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(radioMalhaFechada)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup()
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(sensorAlturaSuperior, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lblTanqueSuperior))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblTanqueInferior)
                            .addComponent(sensorAlturaInferior, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addComponent(btnInterromper, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel7Layout.setVerticalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radioMalhaFechada)
                    .addComponent(radioMalhaAberta))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnInterromper, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblTanqueSuperior)
                    .addComponent(lblTanqueInferior))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(sensorAlturaSuperior, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(sensorAlturaInferior, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);

        jMenu1.setText("Arquivo");

        menuSalvar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        menuSalvar.setText("Salvar");
        menuSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuSalvarActionPerformed(evt);
            }
        });
        jMenu1.add(menuSalvar);

        menuCarregar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        menuCarregar.setText("Carregar");
        menuCarregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuCarregarActionPerformed(evt);
            }
        });
        jMenu1.add(menuCarregar);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Configurações");

        menuConfigurarPortas.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_K, java.awt.event.InputEvent.CTRL_MASK));
        menuConfigurarPortas.setText("Configurar Portas");
        menuConfigurarPortas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuConfigurarPortasActionPerformed(evt);
            }
        });
        jMenu2.add(menuConfigurarPortas);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void radioMalhaAbertaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioMalhaAbertaActionPerformed
        setMalhaAberta();
    }//GEN-LAST:event_radioMalhaAbertaActionPerformed

    private void setMalhaAberta() {
        malhaAtiva = MalhaDeControle.MALHA_ABERTA;
        setMalhaAbertaAtiva();
        setTipoSinal(Sinal.DEGRAU);
    }

    private void radioMalhaFechadaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioMalhaFechadaActionPerformed
        setMalhaFechadaAtiva();
        malhaAtiva = MalhaDeControle.MALHA_FECHADO;
    }//GEN-LAST:event_radioMalhaFechadaActionPerformed

    private void radioDegrauActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioDegrauActionPerformed
        setTipoSinal(Sinal.DEGRAU);
    }//GEN-LAST:event_radioDegrauActionPerformed

    private void radioSenoidalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioSenoidalActionPerformed
        setTipoSinal(Sinal.SENOIDAL);
    }//GEN-LAST:event_radioSenoidalActionPerformed

    private void radioQuadradaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioQuadradaActionPerformed
        setTipoSinal(Sinal.QUADRADA);
    }//GEN-LAST:event_radioQuadradaActionPerformed

    private void radioDenteSerraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioDenteSerraActionPerformed
        setTipoSinal(Sinal.DENTE_DE_SERRA);
    }//GEN-LAST:event_radioDenteSerraActionPerformed

    private void radioAleatorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioAleatorioActionPerformed
        setTipoSinal(Sinal.ALEATORIO);
    }//GEN-LAST:event_radioAleatorioActionPerformed

    private void setTipoSinal(int tipo) {
        tipoDeSinal = tipo;

        if (tipo == Sinal.DEGRAU || tipo == Sinal.ALEATORIO) {
            txtPeriodo.setEnabled(false);
        } else {
            txtPeriodo.setEnabled(true);
        }
    }

    private void btnDefinitSetpointActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDefinitSetpointActionPerformed
        String setpoint = txtSetpoint.getText().trim().replace(",", ".");
        if (!validarEntrada(setpoint)) {
            JOptionPane.showMessageDialog(this, "Setpoint inválido.");
            return;
        }

        handlerMainFrame.setSetpoint(setpoint);
    }//GEN-LAST:event_btnDefinitSetpointActionPerformed

    private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendActionPerformed
        running = true;

        if (malhaAtiva == MalhaDeControle.MALHA_ABERTA) {
            String amplitude = txtAmplitude.getText().trim().replace(",", ".");
            if (!validarEntrada(amplitude)) {
                JOptionPane.showMessageDialog(this, "Amplitude invalida.");
                return;
            }

            String periodo = txtPeriodo.getText().trim().replace(",", ".");
            if (!validarEntrada(periodo)) {
                if (tipoDeSinal == Sinal.DEGRAU || tipoDeSinal == Sinal.ALEATORIO) {
                    periodo = "0";
                } else {
                    JOptionPane.showMessageDialog(this, "Período invalido.");
                    return;
                }
            }

            String tempoAtuacao = txtTempoAtuacao.getText().trim().replace(",", ".");
            if (!validarEntrada(tempoAtuacao)) {
                JOptionPane.showMessageDialog(this, "Tempo de atuação invalido.");
                return;
            }

            handlerMainFrame.startSendingMalhaAberta(amplitude, periodo, tempoAtuacao, tipoDeSinal);
        }
    }//GEN-LAST:event_btnSendActionPerformed

    private void btnInterromperActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInterromperActionPerformed
        running = false;

        handlerMainFrame.stopSendingMalhaAberta();
        btnDefinitSetpoint.setEnabled(false);
    }//GEN-LAST:event_btnInterromperActionPerformed

    private void menuSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuSalvarActionPerformed
        try {
            handlerMainFrame.saveGraphicData();
        } catch (FileNotFoundException ex) {
            LogManager.logErro(ex, "Não foi possível salvar o arquivo com os dados do gráfico.");
            JOptionPane.showMessageDialog(this, "Não foi possíve. salvar o arquivo com os dados do gráfico.");
        } catch (IOException ex) {
            LogManager.logErro(ex, "Não foi possível salvar o arquivo com os dados do gráfico.");
            JOptionPane.showMessageDialog(this, "Não foi possível salvar o arquivo com os dados do gráfico.");
        }
    }//GEN-LAST:event_menuSalvarActionPerformed

    private void menuCarregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuCarregarActionPerformed
        JFileChooser fileChooser = new JFileChooser(new File(ControleConstantes.FILE_CONFIGURACAO));
        fileChooser.setFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                String[] split = f.getName().split("\\.");
                return split[split.length - 1].equals(ControleConstantes.FILE_IDENTIFICADOR_DADOS) || f.isDirectory();
            }

            @Override
            public String getDescription() {
                return "Filtro boladao";
            }
        });

        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int option = fileChooser.showOpenDialog(this);

        if (option == JFileChooser.APPROVE_OPTION) {
            String absolutePath = fileChooser.getSelectedFile().getAbsolutePath();
            try {
                GraphicDataManager dataManager = XMLManager.readObject(absolutePath);
                if (dataManager != null) {
                    OfflineChartsDialog offlineChartsDialog = new OfflineChartsDialog(dataManager, this, false);
                    offlineChartsDialog.setVisible(true);
                }
            } catch (FileNotFoundException ex) {
                JOptionPane.showMessageDialog(this, "Não foi possível carregar dados salvos dos sinais.");
                LogManager.logErro(ex, "Não foi possível carregar dados salvos dos sinais.");
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, "Não foi possível carregar dados salvos dos sinais.");
                LogManager.logErro(ex, "Não foi possível carregar dados salvos dos sinais.");
            }
        }
    }//GEN-LAST:event_menuCarregarActionPerformed

    private void menuConfigurarPortasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuConfigurarPortasActionPerformed
        handlerMainFrame.showDialogoConfiguração();
    }//GEN-LAST:event_menuConfigurarPortasActionPerformed

    private void setMalhaAbertaAtiva() {
        radioAleatorio.setEnabled(true);
        radioDenteSerra.setEnabled(true);
        radioQuadrada.setEnabled(true);
        radioSenoidal.setEnabled(true);
        radioDegrau.setEnabled(true);
        btnSend.setEnabled(true);


        txtTempoAtuacao.setEnabled(true);
        txtAmplitude.setEnabled(true);
        txtPeriodo.setEnabled(true);

        txtSetpoint.setEnabled(false);
        btnDefinitSetpoint.setEnabled(false);
    }

    private void setMalhaFechadaAtiva() {
        radioAleatorio.setEnabled(false);
        radioDenteSerra.setEnabled(false);
        radioQuadrada.setEnabled(false);
        radioSenoidal.setEnabled(false);
        radioDegrau.setEnabled(false);
        btnSend.setEnabled(false);


        txtTempoAtuacao.setEnabled(false);
        txtAmplitude.setEnabled(false);
        txtPeriodo.setEnabled(false);

        txtSetpoint.setEnabled(true);
        btnDefinitSetpoint.setEnabled(true);
    }

    private boolean validarEntrada(String s) {
        try {
            Float.parseFloat(s);
        } catch (NumberFormatException ex) {
            return false;
        }

        return true;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private dca.sistemascontrole.view.components.CustomButton btnDefinitSetpoint;
    private dca.sistemascontrole.view.components.CustomButton btnInterromper;
    private dca.sistemascontrole.view.components.CustomButton btnSend;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel11;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lblTanqueInferior;
    private javax.swing.JLabel lblTanqueSuperior;
    private javax.swing.JMenuItem menuCarregar;
    private javax.swing.JMenuItem menuConfigurarPortas;
    private javax.swing.JMenuItem menuSalvar;
    private dca.sistemascontrole.view.components.GraphicPanel pnlGraficoSensorInferior;
    private dca.sistemascontrole.view.components.GraphicPanel pnlGraficoSensorSuperior;
    private dca.sistemascontrole.view.components.GraphicPanel pnlGraficoSinalControle;
    private javax.swing.JRadioButton radioAleatorio;
    private javax.swing.JRadioButton radioDegrau;
    private javax.swing.JRadioButton radioDenteSerra;
    private javax.swing.JRadioButton radioMalhaAberta;
    private javax.swing.JRadioButton radioMalhaFechada;
    private javax.swing.JRadioButton radioQuadrada;
    private javax.swing.JRadioButton radioSenoidal;
    private dca.sistemascontrole.view.components.SensorAltura sensorAlturaInferior;
    private dca.sistemascontrole.view.components.SensorAltura sensorAlturaSuperior;
    private javax.swing.JTextField txtAmplitude;
    private javax.swing.JTextField txtPeriodo;
    private javax.swing.JTextField txtSetpoint;
    private javax.swing.JTextField txtTempoAtuacao;
    // End of variables declaration//GEN-END:variables
}
